package org.example.StudentManagementSystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.example.StudentManagementSystem.entity.Course;
import org.example.StudentManagementSystem.common.Result;
import org.example.StudentManagementSystem.dto.request.CourseDTO;
import org.example.StudentManagementSystem.service.CourseService;
import org.example.StudentManagementSystem.service.TeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/course")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
@Tag(name = "课程管理", description = "管理系统的课程")
public class CourseController {
    @Autowired
    private CourseService courseService;

    @Autowired
    private TeacherService teacherService;

    /**
     * 将Course转换为CourseDTO
     */
    public CourseDTO convertToDTO(Course course) {
        CourseDTO courseDTO = new CourseDTO();
        BeanUtils.copyProperties(course, courseDTO);
        if (course.getTeacherId() != null) {
            courseDTO.setTeacherName(teacherService.getById(course.getTeacherId()).getName());
        }
        return courseDTO;
    }

    /**
     * 获取课程列表
     */
    @Operation(summary = "获取课程列表", description = "根据分页参数获取课程列表")
    @ApiResponse(responseCode = "200", description = "成功获取课程列表",
            content = @Content(array = @ArraySchema(schema = @Schema(implementation = CourseDTO.class))))
    @GetMapping("")
    public Result getCourseList(@Parameter(description = "页码", required = true) @RequestParam(defaultValue = "1") int page,
                                 @Parameter(description = "每页大小", required = true) @RequestParam(defaultValue = "10") int size) {
        Page<Course> coursePage = courseService.page(Page.of(page, size));
        if (coursePage.getTotal() == 0) {
            return Result.error("暂无数据");
        }
        List<CourseDTO> courseDTOList = coursePage.getRecords().stream().map(this::convertToDTO).collect(Collectors.toList());
        Page<CourseDTO> courseDTOPage = new Page<>();
        courseDTOPage.setCurrent(coursePage.getCurrent());
        courseDTOPage.setSize(coursePage.getSize());
        courseDTOPage.setTotal(coursePage.getTotal());
        courseDTOPage.setRecords(courseDTOList);
        return Result.success(courseDTOPage, "获取课程列表成功");
    }

    /**
     * 获取所有课程
     */
    @Operation(summary = "获取所有课程", description = "获取系统中所有的课程")
    @ApiResponse(responseCode = "200", description = "成功获取所有课程",
            content = @Content(array = @ArraySchema(schema = @Schema(implementation = CourseDTO.class))))
    @GetMapping("/all")
    public Result getAllCourse() {
        List<Course> courseList = courseService.list();
        List<CourseDTO> courseDTOList = courseList.stream().map(this::convertToDTO).collect(Collectors.toList());
        return Result.success(courseDTOList, "获取所有课程成功");
    }

    /**
     * 获取课程详情
     */
    @Operation(summary = "获取课程详情", description = "根据课程ID获取课程详细信息")
    @ApiResponse(responseCode = "200", description = "成功获取课程详情",
            content = @Content(schema = @Schema(implementation = CourseDTO.class)))
    @ApiResponse(responseCode = "404", description = "课程不存在")
    @GetMapping("/{id}")
    public Result getCourseById(@Parameter(description = "课程ID", required = true) @PathVariable int id) {
        Course course = courseService.getById(id);
        if (course == null) {
            return Result.error("没有该课程");
        }
        CourseDTO courseDTO = convertToDTO(course);
        return Result.success(courseDTO, "获取课程成功");
    }

    /**
     * 添加课程
     */
    @Operation(summary = "添加课程", description = "添加一个新的课程")
    @ApiResponse(responseCode = "200", description = "成功添加课程",
            content = @Content(schema = @Schema(implementation = Course.class)))
    @ApiResponse(responseCode = "400", description = "课程名称不能为空")
    @PostMapping("")
    public Result addCourse(@Parameter(description = "课程信息", required = true) @RequestBody Course course) {
        if (course.getName() == null) {
            return Result.error("课程名称不能为空");
        }
        return courseService.save(course) ? Result.success(course, "新增课程成功") : Result.error("新增课程失败");
    }

    /**
     * 修改课程
     */
    @Operation(summary = "修改课程", description = "根据课程ID修改课程信息")
    @ApiResponse(responseCode = "200", description = "成功修改课程",
            content = @Content(schema = @Schema(implementation = Course.class)))
    @ApiResponse(responseCode = "400", description = "课程名称不能为空")
    @PutMapping("/{id}")
    public Result updateCourse(@Parameter(description = "课程ID", required = true) @PathVariable int id,
                               @Parameter(description = "新的课程信息", required = true) @RequestBody Course course) {
        if (course.getName() == null) {
            return Result.error("课程名称不能为空");
        }
        course.setId(id);
        return courseService.updateById(course) ? Result.success(course, "修改课程成功") : Result.error("修改课程失败");
    }

    /**
     * 删除课程
     */
    @Operation(summary = "删除课程", description = "根据课程ID删除指定课程")
    @ApiResponse(responseCode = "200", description = "成功删除课程")
    @ApiResponse(responseCode = "404", description = "课程不存在")
    @DeleteMapping("/{id}")
    public Result deleteCourse(@Parameter(description = "课程ID", required = true) @PathVariable int id) {
        if (courseService.getById(id) == null) {
            return Result.error("该课程不存在");
        }
        return courseService.removeById(id) ? Result.success("删除课程成功") : Result.error("删除课程失败");
    }

    /**
     * 批量删除课程
     */
    @Operation(summary = "批量删除课程", description = "根据课程ID列表批量删除课程")
    @ApiResponse(responseCode = "200", description = "成功批量删除课程")
    @ApiResponse(responseCode = "400", description = "请选择要删除的课程")
    @ApiResponse(responseCode = "404", description = "课程不存在")
    @DeleteMapping("")
    public Result deleteCourses(@Parameter(description = "课程ID列表", required = true) @RequestBody int[] ids) {
        if (ids.length == 0) {
            return Result.error("请选择要删除的课程");
        }
        for (int id : ids) {
            if (courseService.getById(id) == null) {
                return Result.error("该课程不存在");
            }
        }
        List<Integer> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        return courseService.removeByIds(idList) ? Result.success("删除课程成功") : Result.error("删除课程失败");
    }
}
